import {config} from '@/common/config.js'
import store from '@/store/index.js'
import toast from '@/common/utils/toast'
let request = (data = {url: '', method: 'get', params: {}}, header = {}) => {
  header = {
    'content-type': 'application/json;charset=UTF-8',
    'X-Access-Token': store.getters.token || '',
    ...header
  }
  return new Promise(function (resolve, reject) {
    uni.request({
      url: config.api + data.url,
      method: data.method,
      data: data.params,
      header: header,
      success: res => {
        if (res.statusCode === 200) {
          let d = res.data
          if (d.code == 200) {
            resolve(d.result)   //异步操作执行成功
          } else {
            d.message = d.message || '系统异常，请稍后再试'
            if (d.code == 401) {
							toast('请重新登录', () => {
								uni.redirectTo({
								  url: '/pages/login/index'
								});
							})
            } else {
              toast(d.message);
              reject(d)
            }
          }
        } else if (res.statusCode === 401) {
          toast('请重新登录', () => {
            uni.redirectTo({
              url: '/pages/login/index'
            });
          })
        } else {
					toast('网络异常，请稍后再试')
          uni.$emit('z-paging-error-emit')
          reject(res)     //异步操作执行失败
        }
      },
      fail() {
        toast('网络异常，请稍后再试')
        reject()
      }
    })
  });
}
export default request;
